<?php
namespace api\modules\mp\controllers;

use api\modules\mp\models\Transfer;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use Yii;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\web\UnauthorizedHttpException;

class TransferController extends Controller {

    public $enableCsrfValidation = false;

    public function behaviors() {
        return array_merge(parent::behaviors(), [
            [
                'class' => 'yii\filters\auth\QueryParamAuth',
                'tokenParam' => 'session',
            ],
        ]);
    }

    public function beforeAction($action) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return parent::beforeAction($action);
    }

    public function actionIndex() {
        $r = Transfer::getList();
        return [
            'code' => 200,
            'data' => ['list' => $r]
        ];
    }

    public function actionMy() {

    }

    public function actionInfo() {
        $id = Yii::$app->request->get('id');
        $model = Transfer::build(['id' => $id]);
        $info = $model->info();
        return [
            'code' => 200,
            'data' => ['info' => $info]
        ];
    }

    public function actionSave() {
        $data = Yii::$app->request->post();
        $data['openid'] = Yii::$app->user->getIdentity()->openid;
        $model = new Transfer();
        if ($id = ArrayHelper::remove($data, 'id')) {
            $one = Transfer::getOne("id=$id");
            if (!$one) throw new NotFoundHttpException();
            $model->setAttributes($one,false);
            if ($model->openid != $data['openid']) throw new UnauthorizedHttpException();
        }
        $model->load($data, '');
        if ($model->validate()) {
            $model->save();
            return [
                'code' => 200,
                'data' => ['id' => $model->id]
            ];
        } else {
            return [
                'code' => 401,
                'msg' => current($model->getFirstErrors()),
                'field' => key($model->getFirstErrors())
            ];
        }
    }

    public function actionPublish() {
        $id = Yii::$app->request->post('id');
        (new Transfer(['id' => $id]))->publish();
        return ['code' => 200,];
    }

    public function actionCancel() {
        $id = Yii::$app->request->post('id');
        (new Transfer(['id' => $id]))->cancel();
        return ['code' => 200,];
    }

}
